﻿using Intex.Tools;
using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.IO;
namespace WPFExcelReport
{
    public partial class YCAAUTOFSABData : BaseFunction
    {
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        public INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        public string processed = "";
        public string ITXMANDANT = "00", ITXDBVERSION = "50.24", ITXUSER = "INTEXMAP", ITXDATE = "20120723";
        public string ITXLOOMTYPE = "T610  ";
        public string ITXFART = "                    ", ITXGART = "                    ", ITXBART = "                    ";
        public string ITXFVAR = "  ", ITXGVAR = "  ", ITXBVAR = "1 ";
        public string ITXFCOLOR = "          ", ITXGCOLOR = "          ", ITXBCOLOR = "          ";
        public string ITXFFINISH = "          ", ITXCADID = "1";
        public string ITXWBLO = "TX", ITXWBLB = "01";
        SETINTEXDB INTEXDB = new SETINTEXDB();
        public string CADCHAR = " ", ITXCHAR = " ";
        DataRow dwIntexStd = null;
        public Dictionary<string, object> CADTable = new Dictionary<string, object>();
        public Convert2Intex Convert2Intex;
        public DataSet SetExt;
    
        public YCAAUTOFSABData()
            : base()
        {
        }
        public YCAAUTOFSABData(OracleConnection _OracleDB, IntexReptServBLClient _proxy, string userID = "        ")
            : base(_OracleDB, _proxy, userID)
        {
            SetExt = new DataSet();
        }
        public YCAAUTOFSABData(Dictionary<string, object> DicGlobalPara)
            : base(DicGlobalPara)
        {
        }
        #region=============INTEX WS/BS=============================
        public DataSet ResetSetDispo(string setID = "")
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            try
            {
                ArrayList tables = new ArrayList();
                string filePath = Path.Combine(PathHelper.ApplicationPath, @"Report\Interface\PRODSETUP.xls");
                if (!System.IO.File.Exists(filePath))
                {
                    return setReturn;
                }
                if (exAgent == null)
                {
                    exAgent = new ExcelX.ExcelLib.ExcelAgent(filePath);
                }
                setResult = exAgent.LoadDataTableDef(filePath, "");
                filePath = Path.Combine(PathHelper.ApplicationPath, @"Report\Interface\PRODSETUP.XML");
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
                setResult.WriteXml(filePath);
                setResult = new DataSet();
                setResult = LoadSetDispo(setID);
                setReturn.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        public DataSet LoadSetDispo(string setID = "")
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            try
            {
                string filePath = Path.Combine(PathHelper.ApplicationPath, @"Report\Interface\PRODSETUP.XML");
                if (!System.IO.File.Exists(filePath))
                {
                    return setReturn;
                }
                setResult.ReadXml(filePath);
                setReturn.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        public void SaveSetDispo(DataTable tbDispo)
        {
            DataSet setDispo = new DataSet();

            try
            {
                setDispo.Merge(tbDispo);
                string filePath = Path.Combine(PathHelper.ApplicationPath, @"Report\Interface\DATADISPO.XML");
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                    setDispo.WriteXml(filePath);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        #endregion
        public DataSet ConvertToIntex(ref bool success, ref string failreason)
        {
            DataSet setResult = new DataSet();
            DataSet Return = new DataSet();//is used to magage the data to upload to intex 
            DataTable tbGSCOLOR = new DataTable();

            try
            {
                Convert2Intex = new Convert2Intex(SetExt, dwIntexStd, OracleDB, proxy);
                dwIntexStd = Convert2Intex.dwIntexStd;  
                if (SetExt.Tables["ABPOS_EXT"].Rows.Count > 0)
                {
                    setResult = Convert2ABPOS();
                    SetExt.Merge(setResult);
                    if (setResult.Tables.Contains("ABPOS"))
                    {
                        Return.Merge(setResult.Tables["ABPOS"]);
                    }
                    if (setResult.Tables.Contains("ABKOPF"))
                    {
                        Return.Merge(setResult.Tables["ABKOPF"]);
                    }
                    if (setResult.Tables.Contains("ABPR"))
                    {
                        Return.Merge(setResult.Tables["ABPR"]);
                    }
                    if (setResult.Tables.Contains("ABAUFM"))
                    {
                        Return.Merge(setResult.Tables["ABAUFM"]);
                    }
                 
                    if (setResult.Tables.Contains("GAAUF"))
                    {
                        Return.Merge(setResult.Tables["GAAUF"]);
                    }
                    if (setResult.Tables.Contains("WDECK"))
                    {
                        Return.Merge(setResult.Tables["WDECK"]);
                    }

                    if (setResult.Tables.Contains("MDECK"))
                    {
                        Return.Merge(setResult.Tables["MDECK"]);
                    }
                    if (setResult.Tables.Contains("FDECK"))
                    {
                        Return.Merge(setResult.Tables["FDECK"]);
                    }
                    if (setResult.Tables.Contains("ABFOLGE"))
                    {
                        Return.Merge(setResult.Tables["ABFOLGE"]);
                    }
                    if (setResult.Tables.Contains("ICC_ABPOSFS"))
                    {
                        Return.Merge(setResult.Tables["ICC_ABPOSFS"]);
                    }
                    /*8.	分多轮运行，创建必要的二级成衣单
                     * 检查FDECK，WDECK，MDECK，GAAUF的纱线类型，如果是外部生产，继续创建生产单
                     * 如果是采购，创建采购单
                     * 同一个产品的采购单合并采购*/
                } 
            }
            catch (Exception ex)
            {
                success = false;
                EventDispatcher.Instance.RaiseStatus("异常终止", StatusEventType.StopProgress);
                Tracer.Error(ex.StackTrace, ex);
            }
            return Return;
        }
        public DataSet Convert2ABPOS()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            DataSet setTemp = new DataSet();
            string mapID = "ABPOS_MAP";
            DataTable tbMapID = new DataTable();
            tbMapID = SetExt.Tables[mapID];
            DataTable tbNABPOS = new DataTable();
            tbNABPOS.TableName = "ABPOS";
            bool newabk = false;
            string art = "";
            string var = "";
            string color = "";
            string size = "";
            double qty = 100;//默认100件
            int sku = 0;
            string processedabpos = "";
            DataRow nwABPOS = tbNABPOS.NewRow();
        
            string krs = "", lfd = "";
            string client = "00";
            var query = from dwMap in tbMapID.AsEnumerable()
                        where dwMap["FILE"].ToString().Trim().Trim() == "ABPOS"
                        select dwMap;
            var query1 = from dwABPOS_EXT in SetExt.Tables["ABPOS_EXT"].AsEnumerable()
                         select dwABPOS_EXT;
            foreach (DataRow dwABPOS_EXT in query1)
            {
                newabk = false;
                dwABPOS_EXT["ABPMANDANT"] = "00";
                if ((dwABPOS_EXT["ABPART"].ToString().Trim() + dwABPOS_EXT["ABPVAR"].ToString().Trim() + dwABPOS_EXT["ABPFARBE"].ToString().Trim()) == "")
                    continue;
                #region=====获取生产单号码======
                krs = dwABPOS_EXT["ABPAUFKRS"].ToString();
                lfd = dwABPOS_EXT["ABPAUFLFD"].ToString();
                if (!processedabpos.Contains(krs + lfd + ";"))
                {
                    processedabpos += krs + lfd + ";";
                    newabk = true;
                    dwIntexStd["ITXABKRS"] = krs;
                    var query2 = from dwMap in SetExt.Tables["INTEX_MAP"].AsEnumerable()
                                 where dwMap["FILE"].ToString().Trim().Trim() == "INTEXMAP"
                                 && dwMap["FIELD"].ToString().Trim().Trim() == "ITXABLFD"
                                 select dwMap;
                    foreach (DataRow dwRule in query2)
                    {
                        Convert2Intex.GetCovnertValue(ref dwIntexStd, dwRule);
                    }

                    Convert2Intex.SetExt.Tables["INTEXMAP"].Rows[0].ItemArray = dwIntexStd.ItemArray;
                }
                if (dwIntexStd["ITXABKRS"].ToString() == "**")
                {
                    throw new Exception("上传异常终止，请联系管理员!");
                    return setReturn;
                }
                #endregion
                EventDispatcher.Instance.RaiseStatus("转换AB05:" + dwABPOS_EXT["ABPART"].ToString() + "-" + dwABPOS_EXT["ABPFARBE"].ToString(), StatusEventType.RunningProgress);
                foreach (DataRow dwRule in query)
                { 
                    Convert2Intex.GetCovnertValue(ref nwABPOS, dwRule, dwABPOS_EXT);
                } 
                
                EventDispatcher.Instance.RaiseStatus("转换ABPR", StatusEventType.RunningProgress);
                setResult = Convert2ABPR(nwABPOS);
                setReturn.Merge(setResult);

                EventDispatcher.Instance.RaiseStatus("转换Convert2ABAUFM", StatusEventType.RunningProgress);
                setResult = Convert2ABAUFM(nwABPOS);
                setReturn.Merge(setResult);


                #region=====AB15===========
                EventDispatcher.Instance.RaiseStatus("转换Convert2FDECKZ", StatusEventType.RunningProgress);
                setResult = Convert2FDECKZ(nwABPOS);
                setReturn.Merge(setResult);
                #region=======QueryBOM=============
                if (SetExt.Tables.Contains("FSSTUELI_EXT"))
                {
                    SetExt.Tables["FSSTUELI_EXT"].Clear();
                }
                //FSSMANDANT=:FSSMANDANT AND FSSART=:FSSART 
                DataRow rowTemp = INTEXDB.FSSTUELI.NewRow();
                rowTemp["FSSMANDANT"] = "00";
                rowTemp["FSSART"] = dwABPOS_EXT["ABPART"];
                setResult = INTEXDBC.QueryFSSTUELI(rowTemp, 3);
                if (setResult.Tables.Count == 0)
                    continue;
                setResult.Tables[0].TableName = "FSSTUELI_EXT";
                DataTable tbBOM = setResult.Tables[0];
                
                art = dwABPOS_EXT["ABPART"].ToString();
                var = dwABPOS_EXT["ABPVAR"].ToString();
                color = dwABPOS_EXT["ABPFARBE"].ToString();
                size = dwABPOS_EXT["ABPGROE"].ToString();
                bool HasMainFabric = false;
                qty = System.Convert.ToDouble(dwABPOS_EXT["ABPSOLLMENGE7"].ToString());
                #endregion
                DataRow rm = tbBOM.NewRow();
                double px = 1;
                foreach (DataRow dwBOM in tbBOM.Rows)
                {
                    rm.ItemArray = dwBOM.ItemArray;
                    //FSSVAR	FSSFARBE	FSSGROE	FSSAUFM	FSSVERP
                    //FSSMATKZ FSSMART	FSSMVAR	FSSMFARBE FSSMGROE	 	FSSVERBR FSSVBME	FSSVBGRP	FSSVBFKT
                    //FSSVBKZ==G 用量和尺码相关
                    string FSSVAR = rm["FSSVAR"].ToString();
                    string FSSFARBE = rm["FSSFARBE"].ToString().Trim();
                    string FSSGROE = rm["FSSGROE"].ToString();
                    string FSSAUFM = rm["FSSAUFM"].ToString();
                    string FSSVERP = rm["FSSVERP"].ToString();
                    string FSSPOSTYP = rm["FSSPOSTYP"].ToString();
                    //  if (FSSVAR.Trim() != var)
                    //   continue;

                    //============ 
                    string FSSPOS = rm["FSSPOS"].ToString();
                    string FSSMATKZ = rm["FSSMATKZ"].ToString();
                    string FSSMART = rm["FSSMART"].ToString();
                    string FSSMVAR = rm["FSSMVAR"].ToString();
                    string FSSMFARBE = rm["FSSMFARBE"].ToString();
                    string FSSMGROE = rm["FSSMGROE"].ToString();
                    string FSSVERBR = rm["FSSVERBR"].ToString();
                    string FSSVBME = rm["FSSVBME"].ToString();
                    string FSSVBFKT = rm["FSSVBFKT"].ToString();
                    string FSSVERL = rm["FSSVERL"].ToString();
                    px = 1;
                    /*if (FSSMATKZ == "T")
                        px = 0.01;*/
                    FSSVERBR = (Convert.ToDouble(FSSVERBR) *px* Convert.ToDouble(FSSVBFKT) * 0.000001*(1+ Convert.ToDouble(FSSVERL) * 0.0001)).ToString();
                    rm["FSSVERBR"] = FSSVERBR;  
                    //先处理颜色
                    EventDispatcher.Instance.RaiseStatus("处理原料需求" + FSSMART + FSSMVAR + FSSMFARBE, StatusEventType.RunningProgress);
                    DataRow rtp = null;
                    if (SetExt.Tables.Contains("FSSTUELI_EXT"))
                    {
                        SetExt.Tables["FSSTUELI_EXT"].Clear();
                    }
                    DataTable tbFS05EXT = tbBOM.Clone();
                    DataRow rFS05 = tbFS05EXT.NewRow();
                    rFS05.ItemArray = rm.ItemArray;
                    if (FSSFARBE.Trim() == "*")
                    {
                        rFS05["FSSMFARBE"] = color;
                    }
                    tbFS05EXT.Rows.Add(rFS05);
                    SetExt.Merge(tbFS05EXT);
            
                    if (FSSFARBE.Trim() != "")
                    {
                        if (FSSFARBE.Trim() != "*")
                        {
                            if (FSSFARBE.Trim() != color.Trim())
                                continue;
                        }
                    }
                    if (FSSGROE.Trim() != "")
                    {
                        if (FSSGROE.Trim() != "*")
                        {
                            if (FSSGROE.Trim() != size.Trim())
                                continue;
                        }
                    }
                    switch (FSSMATKZ)
                    {
                        case "G"://纱线  
                            setResult = Convert2GAAUF733(nwABPOS);
                            setReturn.Merge(setResult);
                            break;
                        case "F"://面料 
                            HasMainFabric = true;
                            setResult = Convert2WDECK(nwABPOS);
                            if (FSSPOSTYP == "M")
                            {
                                nwABPOS["ABPDMART"] = setResult.Tables[0].Rows[0]["WDART"].ToString();
                                nwABPOS["ABPDMVAR"] = setResult.Tables[0].Rows[0]["WDVAR"].ToString();
                                nwABPOS["ABPDMFARBE"] = setResult.Tables[0].Rows[0]["WDFARBE"].ToString();
                            }
                            setReturn.Merge(setResult);
                            break;
                        case "M"://辅料 
                            setResult = Convert2MDECK(nwABPOS);
                            setReturn.Merge(setResult);
                            break;
                        case "T": 
                            setResult = Convert2FDECKB(nwABPOS);//这个是需求Convert2FDECKB是自身
                            setReturn.Merge(setResult);
                            break;
                        default:
                            break;
                    }
                }
                #endregion
                if (!HasMainFabric)
                {
                    throw new Exception(art+color+size+"没有主面料?");
                    return setReturn;
                }
                EventDispatcher.Instance.RaiseStatus("流程Convert2ABFOLGE", StatusEventType.RunningProgress);

                setResult = Convert2ABFOLGE(nwABPOS);
                setReturn.Merge(setResult);
                var ql = from DataRow row in setResult.Tables["ABFOLGE"].AsEnumerable()
                         where row["ABFLIEFNR"].ToString() != "00000000"
                         select row;
                foreach (DataRow row in ql)
                {
                    nwABPOS["ABPLIEFNR"] = row["ABFLIEFNR"].ToString();
                    nwABPOS["ABPZLO"] = row["ABFLO"].ToString();
                    nwABPOS["ABPZLB"] = row["ABFLB"].ToString(); 
                } 

                tbNABPOS.Rows.Add(nwABPOS);
                if (newabk)
                {
                    EventDispatcher.Instance.RaiseStatus("生产单头信息Convert2ABKOPF", StatusEventType.RunningProgress);
                    setResult = Convert2ABKOPF(nwABPOS);
                    setReturn.Merge(setResult);
                }
                nwABPOS = tbNABPOS.NewRow();
            }
            setReturn.Merge(tbNABPOS);
            tbNABPOS.TableName = "ABPOS_INT";
            processed = "";
            DataSet STemp = new DataSet();
            foreach (DataRow row in tbNABPOS.Rows)
            {
                krs = row["ABPAUFKRS"].ToString();
                lfd = row["ABPAUFLFD"].ToString();
                color=row["ABPFARBE"].ToString();
                size = row["ABPGROE"].ToString().Trim();
                string szqty = row["ABPSOLLMENGE7"].ToString();
                if (!processed.Contains(krs + lfd + color + ";"))
                {
                    processed += krs + lfd + color + ";";
                    setResult = Convert2ABPOSFS(row);
                    STemp.Merge(setResult);
                }
                var qf = from DataRow rx in STemp.Tables["ICC_ABPOSFS"].AsEnumerable()
                         where rx["KRS"].ToString() == krs
                         && rx["LFD"].ToString() == lfd
                         && rx["FARBE"].ToString() == color
                         select rx;
                foreach (DataRow rx in qf)
                {
                    if (rx.Table.Columns.Contains(size))
                    {
                        rx[size] = szqty;
                    }
                }
            }
            setReturn.Merge(STemp);
            return setReturn;
        }
    }
}